package com.xjrsoft.module.prodOrder.controller;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.xjrsoft.common.model.result.R;
import com.xjrsoft.module.prodOrder.dto.AddOrderDto;
import com.xjrsoft.module.prodOrder.dto.UpdateOrderDto;
import com.xjrsoft.module.prodOrder.entity.Order;
import com.xjrsoft.module.prodOrder.entity.OrderProduct;
import com.xjrsoft.module.prodOrder.service.IOrderProductService;
import com.xjrsoft.module.prodOrder.service.IOrderService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author zlf
 * @since 2023-07-14
 */
@RestController
@RequestMapping("/order")
@Api(value = "/order", tags = "订单模块")
@AllArgsConstructor
public class OrderController {

    private final IOrderService orderService;

    private final IOrderProductService orderProductService;

    @PostMapping
    @ApiOperation(value = "新增订单")
    @Transactional
    public R add(@RequestBody AddOrderDto dto) {
        Order order = BeanUtil.toBean(dto, Order.class);
        List<OrderProduct> orderProductList = BeanUtil.copyToList(dto.getProducts(), OrderProduct.class);
        String id = IdWorker.get32UUID();
        if (CollectionUtils.isNotEmpty(orderProductList)) {
            for (OrderProduct orderProduct : orderProductList) {
                orderProduct.setOrderID(id);
                orderProduct.setId(IdWorker.get32UUID());
            }
        }
        order.setOrderID(id);
        order.setOrderAddTime(LocalDateTime.now());
        boolean isSuccess = orderService.save(order);
        if (isSuccess) orderProductService.saveBatch(orderProductList);
        return R.ok(isSuccess);
    }

    @PutMapping
    @ApiOperation(value = "修改订单")
    public R update(@RequestBody UpdateOrderDto dto) {
        String id = dto.getOrderID();
        Order order = BeanUtil.toBean(dto, Order.class);
        List<OrderProduct> orderProductList = BeanUtil.copyToList(dto.getProducts(), OrderProduct.class);
        if (CollectionUtils.isNotEmpty(orderProductList)) {
            for (OrderProduct orderProduct : orderProductList) {
                orderProduct.setOrderID(id);
                orderProduct.setId(IdWorker.get32UUID());
            }
        }
        order.setOrderModifyTime(LocalDateTime.now());
        boolean isSuccess = orderService.updateById(order);
        if (isSuccess) {
            orderProductService.remove(Wrappers.lambdaQuery(OrderProduct.class).eq(OrderProduct::getOrderID, id));
            orderProductService.saveBatch(orderProductList);
        }
        return R.ok(isSuccess);
    }
}
